/*
 * @Author: hongbin
 * @Date: 2023-03-31 19:25:41
 * @LastEditors: hongbin
 * @LastEditTime: 2023-03-31 20:53:55
 * @Description: 删除好友
 */
import { ObjectId, Double } from "mongodb";
import { NextApiRequest, NextApiResponse } from "next";
import { VerifyFields } from "../../../src/api/utils";
import DB from "../mongodb";
import { receiveRequest } from "../utils";

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    if (!receiveRequest(req, res, "POST")) return;

    if (!VerifyFields.has(req.body, ["friendItem", "userId"])) {
        return res.status(500).json("缺少关键字段");
    }

    const db = await DB;
    const date = Date.now();

    //删除聊天室 chatRecord
    const chatRecord = await db.collection("chatRecord").deleteOne({
        _id: new ObjectId(req.body.friendItem.chatRecordId),
    });

    if (!chatRecord.acknowledged) {
        return res.status(200).json({ data: null, msg: "添加好友信息失败", code: -1 });
    }

    // 删除对方
    const delUserFriendList = await db.collection("userInfo").updateOne(
        { _id: new ObjectId(req.body.userId) },
        {
            $pull: {
                friendsList: {
                    date: new Double(req.body.friendItem.date),
                    friendId: req.body.friendItem.friendId,
                    chatRecordId: req.body.friendItem.chatRecordId,
                },
            },
        }
    );
    console.log(delUserFriendList.upsertedCount);
    if (delUserFriendList.acknowledged) {
        // 从对方的列表中删除自己
        // 删除对方
        const delSelfFromFriendList = await db.collection("userInfo").updateOne(
            { _id: new ObjectId(req.body.friendItem.friendId) },
            {
                $pull: {
                    friendsList: {
                        date: new Double(req.body.friendItem.date),
                        friendId: req.body.userId,
                        chatRecordId: req.body.friendItem.chatRecordId,
                    },
                },
            }
        );
        console.log(delUserFriendList.upsertedCount);
        if (delUserFriendList.acknowledged && delSelfFromFriendList.acknowledged) {
            res.status(200).json({ data: "删除好友成功" });
            return;
        }
    }
    res.status(200).json({ data: null, msg: "删除好友信息失败", code: -1 });
}
